layui.config({  // common.js是配置layui扩展模块的目录，每个页面都需要引入
    version: '1_0_0',   // 更新组件缓存，设为true不缓存，也可以设一个固定值
    base: getProjectUrl() + 'assets/module/',
    // closeFooter: 'true',              // 是否关闭页脚
    tabAutoRefresh: 'true',           // 是否切换Tab自动刷新页面
}).extend({
    steps: 'steps/steps',
    notice: 'notice/notice',
    cascader: 'cascader/cascader',
    dropdownEw: 'dropdown/dropdown',
    fileChoose: 'fileChoose/fileChoose',
    Split: 'Split/Split',
    Cropper: 'Cropper/Cropper',
    tagsInput: 'tagsInput/tagsInput',
    citypicker: 'city-picker/city-picker',
    introJs: 'introJs/introJs',
    zTree: 'zTree/zTree',
    cron: 'cron/cron'
}).use(['layer', 'admin', 'notice', 'upload', 'dropdown'], function () {
    window.layer = layui.layer;
    window.admin = layui.admin;
    window.notice = layui.notice;
    window.dropdown = layui.dropdown;
    window.upload = layui.upload;
});

//全局table设置
layui.table.set({
    method: 'post'
    , skin: 'line'
    , toolbar: false
    , defaultToolbar: ['filter']
    , autoSort: false
    , page: true
    , height: "full-140"
    , cellMinWidth: 60
    , limit: 15
    , limits: [15, 10, 20, 25, 30, 35, 40, 45, 50]
    , request: {
        pageName: 'current'
        , limitName: 'size'
    }
});

//全局layer设置
layui.layer.config({
    offset: '200px'
});

/** 获取当前项目的根路径，通过获取layui.js全路径截取assets之前的地址 */
function getProjectUrl() {
    var layuiDir = layui.cache.dir;
    if (!layuiDir) {
        var js = document.scripts, last = js.length - 1, src;
        for (var i = last; i > 0; i--) {
            if (js[i].readyState === 'interactive') {
                src = js[i].src;
                break;
            }
        }
        var jsPath = src || js[last].src;
        layuiDir = jsPath.substring(0, jsPath.lastIndexOf('/') + 1);
    }
    return layuiDir.substring(0, layuiDir.indexOf('assets'));
}

/**
 * 日期空白处理
 * @param util
 * @param date
 * @returns {string|*}
 */
function dateDisplay(util, date) {
    if (date === null) {
        return "-"
    } else {
        return util.toDateString(date);
    }
}

/**
 * 初始化表单中的上传组件
 * @param uploadCp layui 的 upload 模块
 * @param fieldName form 表单当前字段名称
 * @param elemSelector 组件对应的元素，如 '#upload-elem'
 * @param $elemList 上传文件列表 DOM 对象（可为jquery 对象）
 * @param uploadUrl
 * @param bindAction 选择文件按钮（选择器，如 '#elem-btn'）
 * @param $uploadBtnElem 开始上传按钮（jquery 对象）
 */
function initUploadInForm(uploadCp, fieldName, elemSelector, $elemList, uploadUrl, bindAction, $uploadBtnElem, initUploadInForm) {
    var $ = layui.jquery;
    var element = layui.element;
    var uploadListIns = uploadCp.render({
        elem: elemSelector
        , elemList: $elemList //列表元素对象
        , url: uploadUrl
        , multiple: false
        , accept: 'file'
        , auto: false
        , bindAction: bindAction
        , before: function (obj) { //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
            $uploadBtnElem.text("正在上传...");
            $uploadBtnElem.addClass("layui-btn-disabled");
            $uploadBtnElem.attr("disabled", "disabled");
        }
        , choose: function (obj) {
            var that = this;
            //将每次选择的文件追加到文件队列
            var files = this.files = obj.pushFile();
            if (files && Object.getOwnPropertyNames(files).length > 1) {
                himio.notice.error("仅限制上传一个文件");
            } else {
                //读取本地文件
                obj.preview(function (index, file, result) {
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + file.name + '</td>'
                        , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                        , '<td><div class="layui-progress" lay-filter="progress-gen-code-' + fieldName + '"><div class="layui-progress-bar" lay-percent="0%"></div></div></td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                        $uploadBtnElem.text("开始上传");
                        $uploadBtnElem.addClass("layui-btn-disabled");
                        $uploadBtnElem.attr("disabled", "disabled");
                    });

                    that.elemList.append(tr);
                    element.render('progress'); //渲染新加的进度条组件
                });
                $uploadBtnElem.text("开始上传");
                $uploadBtnElem.removeClass("layui-btn-disabled");
                $uploadBtnElem.removeAttr("disabled");
            }

        }
        , done: function (res, index, upload) { //成功的回调
            var that = this;
            if (res.code === 0) { //上传成功
                var tr = that.elemList.find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(3).html('<label class="layui-badge layui-badge-green">上传成功</label>'); //清空操作
                delete this.files[index]; //删除文件队列已经上传成功的文件
                $uploadBtnElem.text("上传成功");
                $uploadBtnElem.removeClass("layui-btn-disabled");
                $uploadBtnElem.addClass("layui-hide");
                if (initUploadInForm) {
                    debugger
                    $("input[name=" + initUploadInForm + "]").val(res.url);
                }
                return;
            }
            this.error(index, upload);
        }
        , allDone: function (obj) { //多文件上传完毕后的状态回调
            // console.log(obj)
        }
        , error: function (index, upload) { //错误回调
            var that = this;
            var tr = that.elemList.find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
        , progress: function (n, elem, e, index) {
            element.progress('progress-gen-code-' + fieldName, n + '%'); //执行进度条。n 即为返回的进度百分比
        }
    });

}

function initXmSelect() {

}

/**
 * 渲染日期组件
 * @param $
 * @param laydate
 */
function renderLayDateCp($, laydate) {
    var $dateComponents = $("[lay-date]");
    var $dcLength = $dateComponents.length;
    if ($dcLength > 0) {
        for (var i = 0; i < $dcLength; i++) {
            var isRange = typeof ($dateComponents.eq(i).attr("lay-date-range")) !== undefined;
            if (isRange) {
                laydate.render({
                    elem: $dateComponents.eq(i)[0],
                    type: 'date',
                    range: '~',
                    trigger: 'click'
                });
            } else {
                laydate.render({
                    elem: $dateComponents.eq(i)[0],
                    type: 'date',
                    trigger: 'click'
                });
            }
        }
    }
}

/**
 * 渲染富文本
 * @param tinymce
 * @param idSelector
 * @param height
 * @param uploadUrl
 */
function renderTinyMce(idSelector, height, uploadUrl) {
    tinyMCE.init({
        //启动自动上传，禁用图片以blob文本存储（数据较大）
        // automatic_uploads: true,
        selector: idSelector,
        height: height,
        branding: false,
        language: 'zh_CN',
        plugins: 'code print preview fullscreen paste searchreplace save autosave link autolink image imagetools media table codesample lists advlist hr charmap emoticons anchor directionality pagebreak quickbars nonbreaking visualblocks visualchars wordcount',
        toolbar: 'fullscreen preview code | undo redo | forecolor backcolor | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | formatselect fontselect fontsizeselect | link image media emoticons charmap anchor pagebreak codesample | ltr rtl',
        toolbar_drawer: 'sliding',
        // images_upload_url: uploadUrl,
        file_picker_types: 'file image media',
        //给返回的相对路径指定它所相对的基本路径
        images_upload_handler: function (blobInfo, succFun, failFun) {
            var xhr, formData;
            var file = blobInfo.blob();//转化为易于理解的file对象
            xhr = new XMLHttpRequest();
            xhr.withCredentials = false;
            xhr.open('POST', uploadUrl);
            xhr.onload = function () {
                var json;
                if (xhr.status !== 200) {
                    himio.notice.error("HTTP Error :" + xhr.status);
                    // failFun('HTTP Error: ' + xhr.status);
                    return;
                }
                json = JSON.parse(xhr.responseText);
                if (!json || typeof json.location != 'string') {
                    himio.notice.error(json.msg);
                    // failFun('Invalid JSON: ' + xhr.responseText);
                    return;
                }
                himio.notice.success(json.msg);
                succFun(json.location);
            };
            formData = new FormData();
            formData.append('file', file, file.name);//此处与源文档不一样
            xhr.send(formData);
        },
        file_picker_callback: function (callback, value, meta) {
            // Provide file and text for the link dialog
            //文件分类
            var filetype = '.pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4';
            //模拟出一个input用于添加本地文件
            var input = document.createElement('input');
            input.setAttribute('type', 'file');
            input.setAttribute('accept', filetype);
            input.click();
            input.onchange = function () {
                var file = this.files[0];
                var xhr, formData;
                console.log(file.name);
                xhr = new XMLHttpRequest();
                xhr.withCredentials = false;
                xhr.open('POST', uploadUrl);
                xhr.onload = function () {
                    var json;
                    if (xhr.status !== 200) {
                        himio.notice.error("HTTP Error :" + xhr.status);
                        return;
                    }
                    json = JSON.parse(xhr.responseText);
                    if (!json || typeof json.location != 'string') {
                        himio.notice.error(json.msg);
                        return;
                    }
                    himio.notice.success(json.msg);
                    callback(json.location, {text: json.fileName});
                };
                formData = new FormData();
                formData.append('file', file, file.name);
                xhr.send(formData);
            };
        }
    });
}

/**
 * table cell 中状态标识转为字典文本显示
 * @param dictList
 * @param curVal
 * @returns {string}
 */
function showDictLabel(dictList, curVal) {
    var filterArray = dictList.filter(function (value) {
        return value.dictValue == curVal;
    });
    var cssClass = filterArray.length > 0 ? filterArray[0].cssClass : "";
    var dictLabel = filterArray.length > 0 ? filterArray[0].dictLabel : "";
    var style = cssClass !== undefined && (cssClass === null || cssClass == "") ? "layui-bg-rim" : "layui-badge layui-bg-" + cssClass;
    return "<label class='" + style + "'>" + dictLabel + "</label>";
}

var himio = {
    notice: {
        success: function (msg, onCloseFunc, overlay) {
            if (!onCloseFunc) {
                onCloseFunc = function () {
                };
            }
            if (overlay === undefined) {
                overlay = false;
            }
            notice.msg(msg, {
                icon: 1,
                overlay: overlay,
                overlayClose: overlay,
                overlayColor: 'rgba(0, 0, 0, 0.4)',
                timeout: 1000,
                onClosing: onCloseFunc
            });
        },
        info: function (msg) {
            notice.msg(msg, {icon: 5, timeout: 2000});
        },
        warn: function (msg) {
            notice.msg(msg, {
                icon: 3,
                overlay: true,
                close: true,
                overlayColor: 'rgba(0, 0, 0, 0.4)',
                overlayClose: true,
                timeout: 2000
            });
        },
        error: function (msg) {
            notice.msg(msg, {
                icon: 2,
                overlay: true,
                close: true,
                overlayColor: 'rgba(0, 0, 0, 0.4)',
                overlayClose: true,
                timeout: false
            });
        },
        loading: function (msg) {
            notice.msg(msg, {
                icon: 4,
                overlay: true,
                close: true,
                overlayColor: 'rgba(0, 0, 0, 0.4)',
                overlayClose: true,
                timeout: false
            });
        },
        resp: function (resp, callback, async) {
            if (resp.code === 0) {
                if (async === undefined || async) {
                    this.success(resp.msg);
                    callback();
                } else {
                    this.success(resp.msg, callback);
                }
            } else {
                this.error(resp.msg);
            }
        }
    }
}

String.prototype.endWith = function (endStr) {
    var d = this.length - endStr.length;
    return (d >= 0 && this.lastIndexOf(endStr) === d);
}


var pwdValid = {
    // 数字正则表达式，只能为0-9数字
    numValid: function (text) {
        var patten = new RegExp(/^[0-9]+$/);
        return patten.test(text);
    },
    // 英文正则表达式，只能为a-z和A-Z字母
    enValid: function (text) {
        var patten = new RegExp(/^[a-zA-Z]+$/);
        return patten.test(text);
    },
    // 英文、数字正则表达式，必须包含（字母，数字）
    enNumValid: function (text) {
        var patten = new RegExp(/^(?=.*[a-zA-Z]+)(?=.*[0-9]+)[a-zA-Z0-9]+$/);
        return patten.test(text);
    },
    // 英文、数字、特殊字符正则表达式，必须包含（字母，数字，特殊字符!@#$%^&*()-=_+）
    charValid: function (text) {
        var patten = new RegExp(/^(?=.*[A-Za-z])(?=.*\d)(?=.*[~!@#\$%\^&\*\(\)\-=_\+])[A-Za-z\d~!@#\$%\^&\*\(\)\-=_\+]{6,}$/);
        return patten.test(text);
    }
}

/** 密码规则范围验证 */
function checkPwd(charType, password) {
    if (charType === 1) {
        if (!pwdValid.numValid(password)) {
            himio.notice.warn("密码只能为0-9数字");
            return false;
        }
    } else if (charType === 2) {
        if (!pwdValid.enValid(password)) {
            himio.notice.warn("密码只能为a-z和A-Z字母");
            return false;
        }
    } else if (charType === 3) {
        if (!pwdValid.enNumValid(password)) {
            himio.notice.warn("密码必须包含字母以及数字");
            return false;
        }
    } else if (charType === 4) {
        if (!pwdValid.charValid(password)) {
            himio.notice.warn("密码必须包含字母、数字、以及特殊符号<font color='red'>~!@#$%^&*()-=_+</font>");
            return false;
        }
    }
    return true;
}